package com.kgc.ssm.shiro;

import com.kgc.ssm.entity.SysUsers;
import com.kgc.ssm.service.SysUsersService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.List;

//自定义用户Realm
public class UserRealm extends AuthorizingRealm {
    @Resource
    private SysUsersService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权开始...");
        //获取用户名
        String userName = (String) principalCollection.getPrimaryPrincipal();
        //根据用户名，查询数据库，获取该用户的权限列表
        List<String> permissionList = userService.findPermissionByName(userName);
        //根据用户名，查询数据库，获取该用户的角色列表
        List<String> roleList = userService.findRolesByName(userName);
//        if ("admin".equals(primaryPrincipal)){
        //获取用户的权限列表
        //创建AuthorizationInfo实现类对象，并设置权限或角色，并返回
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //设置权限列表
        info.addStringPermissions(permissionList);
        info.addRoles(roleList);
        //返回
        return info;
//        }
//        return null;//返回null代表没有任何权限
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("认证开始...");
        //从令牌中获取用户名
        String principal = (String) token.getPrincipal();
        //调用业务层对象，根据用户名查询用户
        SysUsers SysUsers = userService.findByLoginId(principal);
        //判断用户是否为null
        if (SysUsers != null) {
            //用户名存在，接下来继续交给Shiro去验证密码
            return new SimpleAuthenticationInfo(SysUsers.getLoginId(), SysUsers.getPassword(), ByteSource.Util.bytes("Zy,."), this.getName());
        }
        //用户名不匹配，就返回null
        return null;//返回null代表用户名不存在
    }
}
